package com.xie.authority_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xie.authority_system.config.qiniu.QiniuUtils;
import com.xie.authority_system.dao.UserMapper;
import com.xie.authority_system.entity.User;
import com.xie.authority_system.service.UserService;
import com.xie.authority_system.vo.query.UserQueryVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author XIEJINGCHENG
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2024-01-08 14:45:36
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private QiniuUtils qiniuUtils;


    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     */
    @Override
    public User findUserByUserName(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<User> findUserListByPage(IPage<User> page, UserQueryVo userQueryVo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(userQueryVo), "department_id", userQueryVo.getDepartmentId());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo), "username", userQueryVo.getUsername());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo), "real_name", userQueryVo.getRealName());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo), "phone", userQueryVo.getPhone());

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteById(Long id) {
        User user = baseMapper.selectById(id);
        baseMapper.deleteUserRole(id);
        if (baseMapper.deleteById(id) > 0) {
            if (user != null) {
                qiniuUtils.delete(user.getAvatar());
            }

            return true;
        }

        return false;
    }

    @Override
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        baseMapper.deleteUserRole(userId);
        return baseMapper.saveUserRole(userId, roleIds) > 0;
    }

    @Override
    public List<Long> getUserRole(Long userId) {
        return baseMapper.getUserRole(userId);
    }
}
